package reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Scanner;

/**
 * 利用反射机制操作方法
 */
public class ReflectDemo4 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Person p = new Person();
        p.sayHello();
/*
        //1实例化
        Class cls = Class.forName("reflect.Person");
        Object o = cls.newInstance();

        //2调用方法
        Method method = cls.getMethod("sayHello");
        method.invoke(o);

 */
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入类名");
        String className = scanner.nextLine();
        System.out.println("请输入方法名");
        String methodName = scanner.nextLine();

        Class cls = Class.forName(className);
        Object o = cls.newInstance();
        Method method = cls.getMethod(methodName);
        method.invoke(o);
    }
}


